package lzy.impl.smallspring.context.support;

import lzy.impl.smallspring.beans.BeansException;
import lzy.impl.smallspring.beans.factory.ConfigurableListableBeanFactory;
import lzy.impl.smallspring.beans.factory.config.BeanFactoryPostProcessor;
import lzy.impl.smallspring.beans.factory.config.BeanPostProcessor;
import lzy.impl.smallspring.context.ConfigurableApplicationContext;
import lzy.impl.smallspring.core.io.DefaultResourceLoader;

import java.util.Map;

/**
 * 定义了refresh的逻辑：
 * 1. 初始化BeanFactory
 * 2. 执行BeanFactoryPostProcessor
 * 3. 从BeanFactory中取出BeanPostProcessor并注册
 * 4. 预初始化单例对象
 *
 * </p>
 * 此外，这里还集成了DefaultResourceLoader，因此拥有了读取资源的能力
 *
 *
 */
public abstract class AbstractApplicationContext extends DefaultResourceLoader implements ConfigurableApplicationContext {

    @Override
    public void refresh() throws BeansException {
        // 1. 创建 BeanFactory，并加载 BeanDefinition
        refreshBeanFactory();

        // 2. 获取 BeanFactory
        ConfigurableListableBeanFactory beanFactory = getBeanFactory();

        // 3. 在 Bean 实例化之前，执行 BeanFactoryPostProcessor (Invoke factory processors registered as beans in the context.)
        invokeBeanFactoryPostProcessors(beanFactory);

        // 4. BeanPostProcessor 需要提前于其他 Bean 对象实例化之前执行注册操作
        registerBeanPostProcessors(beanFactory);

        // 5. 提前实例化单例Bean对象
        beanFactory.preInstantiateSingletons();
    }

    protected abstract void refreshBeanFactory();

    protected abstract ConfigurableListableBeanFactory getBeanFactory();

    /**
     * BPP本身也是Bean！先把它们创建好，才能对所有的Bean进行实例化后处理
     *
     * @param beanFactory
     */
    private void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        for (BeanPostProcessor beanPostProcessor : beanFactory.getBeansOfType(BeanPostProcessor.class).values()) {
            beanFactory.addBeanPostProcessors(beanPostProcessor);
        }

    }

    /**
     * BFPP也是Bean，但是由于可以再它们初始化完成后立即使用，所以BFPP的组装和使用都在这里
     *
     * @param beanFactory
     */
    private void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        for (BeanFactoryPostProcessor beanFactoryPostProcessor : beanFactory.getBeansOfType(BeanFactoryPostProcessor.class).values()) {
            beanFactoryPostProcessor.postProcessBeanFactory(beanFactory);
        }
    }

    @Override
    public Object getBean(String name) throws BeansException {
        return null;
    }

    @Override
    public Object getBean(String name, Object... args) throws BeansException {
        return null;
    }

    @Override
    public <T> T getBean(String name, Class<T> requiredType) throws BeansException {
        return null;
    }

    @Override
    public <T> Map<String, T> getBeansOfType(Class<T> type) throws BeansException {
        return null;
    }


}
